package com.mdp.arc.archive.ctrl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.arc.archive.entity.Archive;
import com.mdp.arc.archive.entity.ArchiveCollect;
import com.mdp.arc.archive.service.ArchiveCalcService;
import com.mdp.arc.archive.service.ArchiveCollectService;
import com.mdp.arc.archive.service.ArchiveService;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.msg.client.PushNotifyMsgService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.mdp.core.utils.BaseUtils.toMap;

/**
 * url编制采用rest风格,如对arc_archive_collect 文章收藏人员列表的操作有增删改查,对应的url分别为:<br>
 * 组织 com.mdp  顶级模块 arc 大模块 archive 小模块 <br>
 * 实体 ArchiveCollect 表 arc_archive_collect 当前主键(包括多主键): archive_id,userid; 
 ***/
@RestController("arc.archive.archiveCollectController")
@RequestMapping(value="/*/arc/archive/archiveCollect")
@Api(tags={"文章收藏人员列表操作接口"})
public class ArchiveCollectController {
	
	static Logger logger =LoggerFactory.getLogger(ArchiveCollectController.class);
	
	@Autowired
	private ArchiveCollectService archiveCollectService;

	@Autowired
	PushNotifyMsgService pushNotifyMsgService;

	@Autowired
	ArchiveService archiveService;

	Map<String,Object> fieldsMap = toMap(new ArchiveCollect());
 
	
	@ApiOperation( value = "查询文章收藏人员列表信息列表",notes=" ")
	@ApiEntityParams( ArchiveCollect.class )
	@ApiImplicitParams({
			@ApiImplicitParam(name="pageSize",value="每页大小，默认20条",required=false),
			@ApiImplicitParam(name="pageNum",value="当前页码,从1开始",required=false),
			@ApiImplicitParam(name="total",value="总记录数,服务器端收到0时，会自动计算总记录数，如果上传>0的不自动计算",required=false),
			@ApiImplicitParam(name="count",value="是否计算总记录条数，如果count=true,则计算计算总条数，如果count=false 则不计算",required=false),
			@ApiImplicitParam(name="orderBy",value="排序列 如性别、学生编号排序 orderBy = sex desc,student desc",required=false),
 	})
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveCollect.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listArchiveCollect( @ApiIgnore @RequestParam Map<String,Object> params ){
		
		
		RequestUtils.transformArray(params, "pkList");
		IPage page= QueryTools.initPage(params);
		List<Map<String,Object>>	datas = archiveCollectService.selectListMapByWhere(page,QueryTools.initQueryWrapper(ArchiveCollect.class,params),params);	//列出ArchiveCollect列表
		
		return Result.ok().setData(datas);
	}
	
 

	@ApiOperation( value = "新增一条文章收藏人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveCollect.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addArchiveCollect(@RequestBody ArchiveCollect archiveCollect) {
		
		
		try{
			if(!StringUtils.hasText(archiveCollect.getArchiveId())){
				return Result.error("archiveId-0","文章编号不能为空");
			}
			User user=LoginUtils.getCurrentUserInfo();
			archiveCollect.setUserid(user.getUserid());
			archiveCollect.setCtime(new Date());
			if(archiveCollectService.selectOneObject(archiveCollect) !=null ){
				return Result.error("pk-exists","已收藏");
			}

			archiveCollectService.insert(archiveCollect);
			ArchiveCalcService.collectSet.add(archiveCollect.getArchiveId());
			Archive archiveDb=archiveService.selectOneById(archiveCollect.getArchiveId());
			if(!user.getUserid().equals(archiveDb.getUserid())){
				pushNotifyMsgService.pushMsg(user, archiveDb.getUserid(), archiveDb.getAuthorName(),user.getUsername()+"收藏了文章："+archiveDb.getArchiveTitle(),null);
			}

			return Result.ok().setData(archiveCollect);
		}catch (BizException e) {
			logger.error("",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("",e);
			return Result.error(e.getMessage());

		}
	}

	@ApiOperation( value = "删除一条文章收藏人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")
	}) 
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delArchiveCollect(@RequestBody ArchiveCollect archiveCollect){
		
		
		try{
            if(!StringUtils.hasText(archiveCollect.getArchiveId())) {
                 return Result.error("pk-not-exists","请上送主键参数archiveId");
            }
			User user=LoginUtils.getCurrentUserInfo();
			archiveCollect.setUserid(user.getUserid());
            ArchiveCollect archiveCollectDb = archiveCollectService.selectOneObject(archiveCollect);
            if( archiveCollectDb == null ){
                return Result.error("data-not-exists","已取消收藏");
            }
			archiveCollectService.deleteByPk(archiveCollect);
		}catch (BizException e) {
		logger.error("",e);
		return Result.error(e);
	}catch (Exception e) {
		logger.error("",e);
		return Result.error(e.getMessage());

	}  
		return Result.ok();
	}

	
	/**
	@ApiOperation( value = "根据主键修改一条文章收藏人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveCollect.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editArchiveCollect(@RequestBody ArchiveCollect archiveCollect) {
		
		
		try{
            if(!StringUtils.hasText(archiveCollect.getArchiveId())) {
                 return failed("pk-not-exists","请上送主键参数archiveId");
            }
            if(!StringUtils.hasText(archiveCollect.getUserid())) {
                 return failed("pk-not-exists","请上送主键参数userid");
            }
            ArchiveCollect archiveCollectDb = archiveCollectService.selectOneObject(archiveCollect);
            if( archiveCollectDb == null ){
                return failed("data-not-exists","数据不存在，无法修改");
            }
			archiveCollectService.updateSomeFieldByPk(archiveCollect);
			return Result.ok().setData(archiveCollect);
		}catch (BizException e) {
		logger.error("",e);
		return Result.error(e);
	}catch (Exception e) {
		logger.error("",e);
		return Result.error(e.getMessage());

	}  
		return Result.ok();
	}
	*/

	/**
    @ApiOperation( value = "批量修改某些字段",notes="")
    @ApiEntityParams( value = ArchiveCollect.class, props={ }, remark = "文章收藏人员列表", paramType = "body" )
	@ApiResponses({
			@ApiResponse(code = 200,response=ArchiveCollect.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	})
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields( @ApiIgnore @RequestBody Map<String,Object> archiveCollectMap) {
		
		
		try{
			List<Map<String,Object>> pkList= (List<Map<String,Object>>) archiveCollectMap.get("pkList");
			if(pkList==null || pkList.size()==0){
				return failed("pkList-0","pkList不能为空");
			}

			Set<String> fields=new HashSet<>();
            fields.add("archiveId");
            fields.add("userid");
			for (String fieldName : archiveCollectMap.keySet()) {
				if(fields.contains(fieldName)){
					return failed(fieldName+"-no-edit",fieldName+"不允许修改");
				}
			}
			Set<String> fieldKey=archiveCollectMap.keySet().stream().filter(i-> fieldsMap.containsKey(i)).collect(Collectors.toSet());
			fieldKey=fieldKey.stream().filter(i->!StringUtils.isEmpty(archiveCollectMap.get(i) )).collect(Collectors.toSet());

			if(fieldKey.size()<=0) {
				return failed("fieldKey-0","没有需要更新的字段");
 			}
			ArchiveCollect archiveCollect = fromMap(archiveCollectMap,ArchiveCollect.class);
			List<ArchiveCollect> archiveCollectsDb=archiveCollectService.selectListByIds(pkList);
			if(archiveCollectsDb==null ||archiveCollectsDb.size()==0){
				return failed("data-0","记录已不存在");
			}
			List<ArchiveCollect> can=new ArrayList<>();
			List<ArchiveCollect> no=new ArrayList<>();
			User user = LoginUtils.getCurrentUserInfo();
			for (ArchiveCollect archiveCollectDb : archiveCollectsDb) {
				Tips tips2 = new Tips("检查通过"); 
				if(!tips2.isOk()){
				    no.add(archiveCollectDb); 
				}else{
					can.add(archiveCollectDb);
				}
			}
			if(can.size()>0){
                archiveCollectMap.put("pkList",can.stream().map(i->map( "archiveId",i.getArchiveId(),  "userid",i.getUserid())).collect(Collectors.toList()));
			    archiveCollectService.editSomeFields(archiveCollectMap); 
			}
			List<String> msgs=new ArrayList<>();
			if(can.size()>0){
				msgs.add(String.format("成功更新以下%s条数据",can.size()));
			}
			if(no.size()>0){
				msgs.add(String.format("以下%s个数据无权限更新",no.size()));
			}
			if(can.size()>0){
				return Result.ok(msgs.stream().collect(Collectors.joining()));
			}else {
				return Result.error(msgs.stream().collect(Collectors.joining()));
			}
			//return Result.ok().setData(xmMenu);
		}catch (BizException e) { 
			logger.error("",e);
			return Result.error(e);
		}catch (Exception e) { 
			logger.error("",e);
			return Result.error(e.getMessage());
		}
		return Result.ok();
	}
	*/

	/**
	@ApiOperation( value = "根据主键列表批量删除文章收藏人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")
	}) 
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelArchiveCollect(@RequestBody List<ArchiveCollect> archiveCollects) {
		
        
        try{ 
            if(archiveCollects.size()<=0){
                return failed("data-0","请上送待删除数据列表");
            }
             List<ArchiveCollect> datasDb=archiveCollectService.selectListByIds(archiveCollects.stream().map(i->map( "archiveId",i.getArchiveId() ,  "userid",i.getUserid() )).collect(Collectors.toList()));

            List<ArchiveCollect> can=new ArrayList<>();
            List<ArchiveCollect> no=new ArrayList<>();
            for (ArchiveCollect data : datasDb) {
                if(true){
                    can.add(data);
                }else{
                    no.add(data);
                } 
            }
            List<String> msgs=new ArrayList<>();
            if(can.size()>0){
                archiveCollectService.batchDelete(can);
                msgs.add(String.format("成功删除%s条数据.",can.size()));
            }
    
            if(no.size()>0){ 
                msgs.add(String.format("以下%s条数据不能删除.【%s】",no.size(),no.stream().map(i-> i.getArchiveId() +" "+ i.getUserid() ).collect(Collectors.joining(","))));
            }
            if(can.size()>0){
                 return Result.ok(msgs.stream().collect(Collectors.joining()));
            }else {
                return Result.error(msgs.stream().collect(Collectors.joining()));
            }
        }catch (BizException e) { 
            tips=e.getTips();
            logger.error("",e);
        }catch (Exception e) {
            return Result.error(e.getMessage());
            logger.error("",e);
        }  
        m.put("tips", tips);
        return m;
	} 
	*/
}
